import router from './router';
import store from './store';
import {Message} from 'element-ui';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import {getToken, setToken, removeToken} from '@/utils/auth'; // get token from cookie
import { getMenuList } from "@/api/menu"; // 获取菜单
import { formatRouter, asyncRoutes } from '@/router'; // 格式化菜单
import getPageTitle from '@/utils/get-page-title';
import {get} from 'sortablejs';

NProgress.configure ({showSpinner: false}); // NProgress Configuration

const whiteList = ['/login', '/auth-redirect']; // no redirect whitelist

router.beforeEach (async (to, from, next) => {
  // start progress bar
  NProgress.start ();

  // set page title
  document.title = getPageTitle (to.meta.title);

  // determine whether the user has logged in
  const res = await getMenuList();
  // console.log("asyncRoutes1:", asyncRoutes);
  const menu = formatRouter(res.data.items);
  // console.log("asyncRoutes2:", menu, asyncRoutes);
  if (getToken ()) {
    if (to.path === '/login') {
      next ({path: '/'});
      NProgress.done ();
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0;
      if (hasRoles) {
        next ();
      } else {
        try {
          // 获取用户信息
          // 角色必须是一个数组
          const {roles} = await store.dispatch ('user/getInfo');
          // console.log(roles, 'roles');
          // 根据roles权限生成可访问的路由表
          const accessRoutes = await store.dispatch (
            'permission/generateRoutes',
            roles
          );

          // 动态添加可访问路由表
          router.addRoutes (accessRoutes);

          // hack方法 确保addRoutes已完成
          next ({...to, replace: true});
        } catch (error) {
          // remove token and go to login page to re-login
          // 移出 token 并跳转到登录页
          await store.dispatch ('user/resetToken');
          Message.error (error || 'Has Error');
          next (`/login?redirect=${to.path}`);
          NProgress.done ();
        }
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf (to.path) !== -1) {
      // 在免登录白名单，直接进入
      next ();
    } else {
      // 否则全部重定向到登录页
      next (`/login?redirect=${to.path}`);
      NProgress.done ();
    }
  }
});

router.afterEach (() => {
  // finish progress bar
  NProgress.done ();
});
